How to setTimeout Synchronously in JavaScript
· One min read
Overview
In JavaScript, setTimeout is an asynchronous function, meaning it does not block the execution of subsequent code. However, you can achieve a synchronous-like delay using Promises and the async/await pattern.
Implementation
You can create a sleep function that returns a Promise, which resolves after the specified timeout:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Then, use await inside an async function to pause execution until the Promise resolves:
async function demo() {
await sleep(5000);
alert('This should be the second one');
}
demo();
Explanation
- The
sleepfunction returns a Promise that resolves aftermsmilliseconds. - Inside the
demofunction,await sleep(5000);pauses execution for 5 seconds. - After the delay, the alert message is displayed.
Using await ensures that the execution flow appears synchronous, making the code more readable and manageable in asynchronous scenarios.
